<?php

/**
 * 金币统计
 */

namespace app\command\count;


use app\common\model\CountGold;
use app\common\model\MoneyRecordModel;
use org\DingDingRobot;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class CountGoldCommand extends Command
{
    protected function configure()
    {
        $this->setName('count_gold')
            ->addArgument('begin_day', Argument::OPTIONAL, '指定执行开始日期')
            ->addArgument('end_day', Argument::OPTIONAL, '指定执行截至日期')
            ->setDescription('金币统计');
    }

    /**
     * @param Input $input
     * @param Output $output
     * @return int|void|null
     */
    protected function execute(Input $input, Output $output)
    {
        $begin_day = $input->getArgument('begin_day');
        $end_day   = $input->getArgument('end_day');

        if (empty($end_day) && empty($begin_day)) {

            # 定时任务配置在凌晨之后，默认跑前一天的数据
            $date = date('Y-m-d', strtotime(date('Y-m-d') . ' -1 day'));
            $this->buildData($date, $output);

        } elseif (!empty($begin_day) && !empty($end_day)) {

            # 跑指定日期范围的数据
            $begin_time = strtotime(date('Y-m-d 00:00:00', strtotime($begin_day)));
            $end_time   = strtotime(date('Y-m-d 23:59:59', strtotime($end_day)));

            for ($i = $begin_time; $i < $end_time; $i += 86400) {
                $date = date('Y-m-d', $i);
                $this->buildData($date, $output);
                $output->info($date);
            }

        } elseif (!empty($begin_day)) {
            # 跑指定日期的数据
            $date = date('Y-m-d', strtotime($begin_day));
            $this->buildData($date, $output);
            $output->info($date);
        }
    }

    /**
     * 金币统计
     * 日期    领取人数    当日发放    阅读新闻    签到    邀请码    看广告（任务）    看新闻（任务）    闯关（任务）    抽奖（任务）    邀请
     * 金币    钻石    碎片    金币    金币    钻石    金币    金币    钻石    金币    钻石    金币    碎片    金币    钻石    碎片    金币    钻石
     * @param string $date
     * @param Output $output
     */
    protected function buildData(string $date, Output $output)
    {
        try {
            $model = MoneyRecordModel::where([
                ["write_date", '=', $date],
                ['method', 'IN', array_keys(MoneyRecordModel::$methodLabel)],
            ]);

            $field     = [
                "count(DISTINCT member_id) receive_num", # 领取人数
                "sum(if(currency = 0,amount,0)) day_gold_num", # 当日发放- 金币
                "sum(if(currency = 3,amount,0)) day_diamond_num", # 当日发放- 钻石
                # 阅读新闻
                "sum(if(method = 4,amount,0)) read_gold_num",
                # 签到
                "sum(if(method = 0 and currency = 0,amount,0)) duty_gold_num",
                "sum(if(method = 0 and currency = 3,amount,0)) duty_diamond_num",
                # 邀请码
                "sum(if(method = 1,amount,0)) invite_code_gold_num",
                # 看广告（任务）
                "sum(if(method = 19 and currency = 0,amount,0)) adv_gold_num",
                "sum(if(method = 19 and currency = 3,amount,0)) adv_diamond_num",

                # 看新闻（阅读任务）
                "sum(if(method = 16 and currency = 0,amount,0)) read_news_gold_num",
                "sum(if(method = 16 and currency = 3,amount,0)) read_news_diamond_num",

                # 闯关
                # 抽奖

                # 邀请
                "sum(if(method = 8 and currency = 0,amount,0)) invite_gold_num",
                "sum(if(method = 8 and currency = 3,amount,0)) invite_diamond_num",
            ];
            $user_data = $model->field($field)->find();

            $data = [
                'record_date'           => $date,
                'receive_num'           => $user_data['receive_num'] ?? 0,
                'day_gold_num'          => $user_data['day_gold_num'] ?? 0,
                'day_diamond_num'       => $user_data['day_diamond_num'] ?? 0,
                'day_scrap_num'         => $user_data['day_scrap_num'] ?? 0,
                'read_gold_num'         => $user_data['read_gold_num'] ?? 0,
                'duty_gold_num'         => $user_data['duty_gold_num'] ?? 0,
                'duty_diamond_num'      => $user_data['duty_diamond_num'] ?? 0,
                'invite_code_gold_num'  => $user_data['invite_code_gold_num'] ?? 0,
                'adv_gold_num'          => $user_data['adv_gold_num'] ?? 0,
                'adv_diamond_num'       => $user_data['adv_diamond_num'] ?? 0,
                'read_news_gold_num'    => $user_data['read_news_gold_num'] ?? 0,
                'read_news_diamond_num' => $user_data['read_news_diamond_num'] ?? 0,
                'barrier_gold_num'      => $user_data['barrier_gold_num'] ?? 0,
                'barrier_scrap_num'     => $user_data['barrier_scrap_num'] ?? 0,
                'lottery_gold_num'      => $user_data['lottery_gold_num'] ?? 0,
                'lottery_diamond_num'   => $user_data['lottery_diamond_num'] ?? 0,
                'lottery_scrap_num'     => $user_data['lottery_scrap_num'] ?? 0,
                'invite_gold_num'       => $user_data['invite_gold_num'] ?? 0,
                'invite_diamond_num'    => $user_data['invite_diamond_num'] ?? 0,
                'create_time'           => time(),
            ];

            $row = CountGold::where("record_date", $date)->find();
            if ($row) {
                CountGold::update($data, ['id' => $row['id']]);
            } else {
                CountGold::insert($data);
            }

            DingDingRobot::getInstance()->pushText("金币统计脚本,执行完成,日期:{$date}");
        } catch (DataNotFoundException $e) {
            DingDingRobot::getInstance()->pushText("金币统计脚本异常，日期:{$date},内容：" . $e->getMessage());
        } catch (ModelNotFoundException $e) {
            DingDingRobot::getInstance()->pushText("金币统计脚本异常，日期:{$date},内容：" . $e->getMessage());
        } catch (DbException $e) {
            DingDingRobot::getInstance()->pushText("金币统计脚本异常，日期:{$date},内容：" . $e->getMessage());
        }
    }
}
